<template>
  <div class="order-common-container" v-loading="loading">
    <div class="order-common" v-for="(item, index) in orderList" :key="index">
      <div class="order-common-header">
        <div class="order-common-header-left">
          <div>订单号:{{ item.order_sn }}</div>
          <div class="order-common-header-left-time">下单时间: {{ formatDate(item.create_time) }}</div>
        </div>
        <div
          :class="{
            'order-common-header-todo': item.status === 1,
            'order-common-header-cancel': item.status === 4,
            'order-common-header-done': item.status === 2,
          }"
        >
          {{ getOrderStatus(item.status) }}
        </div>
      </div>
      <div class="order-common-body">
        <div class="order-common-body-left">
          <div class="image">
            <img :src="item.goodsimage" alt="" />
          </div>
          <div class="content">
            <div>{{ item.goodsname }}</div>
            <!-- <div class="content-tags">
              <div v-for="(v, i) in item.tags" :key="i">{{ v }}</div>
            </div> -->
          </div>
        </div>
        <div class="order-common-body-right">
          <div class="order-common-body-right-price">¥{{ item.total_price }}</div>
          <div class="order-common-body-right-btns">
            <div v-if="item.status == 1">
              <CommonBtn @click="handlePay(item)">立即支付</CommonBtn>
            </div>
            <div v-if="item.status == 1" class="order-common-body-right-btns-cancel"><CommonBtn :dashboard="true" @click="cancelOrder(item)">取消订单</CommonBtn></div>
            <CommonBtn @click="downloadInvoice(item)" v-if="item.invoice == 2">{{ item.invoice == 2 ? '下载支票' : '申请开票' }}</CommonBtn>
          </div>
        </div>
      </div>
    </div>

    <!-- 支付弹窗 -->
    <el-dialog v-model="paymentDialogVisible" :title="paymentMethod === 'alipay' ? '支付宝支付' : '微信支付'" width="400px" center>
          <div class="payment-dialog-content">
              <div class="qr-code">
                  <img v-if="qrCodeDataUrl" :src="qrCodeDataUrl" alt="支付二维码" />
              </div>
              <p>扫描二维码完成支付</p>
              <div class="payment-amount">¥{{ currentOrder.total_price }} CNY</div>
          </div>
      </el-dialog>

      <!-- 支付成功弹窗 -->
      <el-dialog v-model="successDialogVisible" width="400px" center>
          <div class="success-dialog-content">
              <div class="success-icon">
              <el-icon color="#FFFF" :size="40"><Check /></el-icon>
              </div>
              <h3>支付成功</h3>
              <p>付款金额：¥{{ currentOrder.total_price }}</p>
              <el-button type="primary" @click="goToOrder">查看订单</el-button>
          </div>
      </el-dialog>
  </div>
</template>
<script setup>
import { ref, onBeforeUnmount } from "vue";
import CommonBtn from "@/components/CommonBtn";
import { myInvoiceApply, myOrderCancel, myOrderDetail } from "@/service/personalCenter"
import { formatDate } from "@/utils/index.js";
import QRCode from 'qrcode';
import { ElMessage } from "element-plus";
import { useRouter } from 'vue-router';

const router = useRouter();
const paymentDialogVisible = ref(false);
const successDialogVisible = ref(false);
const qrCodeDataUrl = ref('');
const payLoading = ref(false);
const currentOrder = ref({});
const pollTimer = ref(null);
const orderId = ref(null); 

const props = defineProps({
  orderList: {
    type: Array,
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['orderCanceled', 'refreshOrders']);

const getOrderStatus = (status) => {
  switch (status) {
    case 1:
      return "待支付";
    case 4:
      return "已取消";
    case 2:
      return "已完成";
    case 3:
      return "已关闭";
    default:
      return "未知状态";
  }
};

const downloadInvoice = (item) => {
  if(item.invoice == 2) {
    const url = item.invoice_url
    if (!url) {
      ElMessage.error('支票链接不存在')
      return
    }
    // 创建一个隐藏的a标签用于下载
    const link = document.createElement('a')
    link.href = url
    link.download = `支票_${item.order_sn}.pdf`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } else {
    myInvoiceApply({id: item.id}).then((res) => {
      if(res.code == '000000') {
        ElMessage.success('申请成功')
      }
    });
  }
};

const handlePay = (item) => {
  currentOrder.value = item;
  orderId.value = item.id;
  if (item.payway == 2 && item.url) {
      paymentDialogVisible.value = true;
      // 生成二维码
      QRCode.toDataURL(item.url, { width: 200 })
      .then(url => {
          
          qrCodeDataUrl.value = url;
          // 开始轮询订单状态
          startPollOrderStatus();
      })
      .catch(err => {
          console.error('生成二维码失败:', err);
      });
  } else if(item.payway == 1) {
      // 支付宝支付
      window.open(item.url, '_blank');
  }
} 

const goToOrder = () => {
  successDialogVisible.value = false;
  emit('refreshOrders');
  router.push(`/personCenter/Center?personCenterValue=5`);
}

// 轮询订单状态
const startPollOrderStatus = () => {
  // 清除可能存在的定时器
  if (pollTimer.value) {
    clearInterval(pollTimer.value);
  }
  
  // 设置轮询间隔，每2秒查询一次
  pollTimer.value = setInterval(() => {
    if (!orderId.value || !paymentDialogVisible.value) {
      clearInterval(pollTimer.value);
      return;
    }
    
    checkOrderStatus();
  }, 2000);
}

// 检查订单状态
const checkOrderStatus = () => {
  myOrderDetail({ id: orderId.value }).then(res => {
    console.log('订单状态:', res);
    if (res.code === '000000') {
      // 订单状态: 1-待支付, 2-已完成, 3-已关闭, 4-已取消
      if (res.data && res.data.status === 2) {
        // 支付成功，停止轮询
        clearInterval(pollTimer.value);
        // 关闭支付码弹窗
        paymentDialogVisible.value = false;
        // 显示支付成功弹窗
        successDialogVisible.value = true;
        // 通知父组件刷新订单列表
        emit('refreshOrders');
        ElMessage.success('支付成功');
      } else if (res.data && (res.data.status === 3 || res.data.status === 4)) {
        // 订单已关闭或已取消，停止轮询
        clearInterval(pollTimer.value);
        paymentDialogVisible.value = false;
        ElMessage.warning('订单已关闭或已取消');
      }
    }
  }).catch(err => {
    console.error('查询订单状态失败:', err);
  });
}

onBeforeUnmount(() => {
    if (pollTimer.value) {
      clearInterval(pollTimer.value);
    }
});

const cancelOrder = (item) => {
  myOrderCancel({id: item.id}).then((res) => {
    if(res.code == '000000') {
      ElMessage.success('取消成功')
      emit('orderCanceled', item.id)
    }
  });
}
</script>
<style lang="scss" scoped>
.order-common {
  margin: 10px;
  border-bottom: 1px solid #f4f4f4;
  padding-bottom: 10px;
  &-header {
    display: flex;
    justify-content: space-between;
    &-left {
      display: flex;
      color: var(--otherFontColor);
      font-size: var(--default12px);
      margin-bottom: 10px;
      &-time {
        margin-left: 10px;
      }
    }
    &-todo {
      color: #e52121;
      font-size: 12px;
      font-weight: 600;
    }
    &-cancel {
      color: #d9d9d9;
      font-size: 12px;
    }
    &-done {
      color: var(--main-color);
      font-size: 12px;
    }
  }
  &-body {
    display: flex;
    justify-content: space-between;
    &-left {
      display: flex;
      .image {
        width: 80px;
        height: 60px;
        background-color: #d9d9d9;
        border-radius: 4px;
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      .content {
        flex: 1;
        margin-left: 10px;
        &-tags {
          display: flex;
          gap: 10px;
          margin-top: 8px;
          > div {
            color: #126983;
            background: rgba(18, 105, 131, 0.1019607843);
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
          }
        }
      }
    }
    &-right {
      display: flex;
      min-width: 150px;
      &-price {
        color: #e52121;
        font-size: 16px;
        font-weight: 600;
      }
      &-btns {
        margin-left: 14px;
        &-cancel {
          margin-top: 8px;
        }
      }
    }
  }
}
  .payment-dialog-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
  }
  
  .qr-code {
    width: 200px;
    height: 200px;
    background-color: #eee;
    margin-bottom: 20px;
  }
  
  .payment-amount {
    font-size: 18px;
    color: #f56c6c;
    font-weight: 500;
    margin-top: 10px;
  }
  
  // 支付成功弹窗样式
  .success-dialog-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
  }
  
  .success-icon {
    margin-bottom: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background-color: #52C41A;
  }
  
  .success-dialog-content h3 {
    margin-bottom: 15px;
    font-weight: 500;
  }
  
  .success-dialog-content p {
    margin-bottom: 20px;
    color: #666;
  }
:deep(.el-dialog__header.show-close) {
    padding-right: 0px;
}
</style>
